import 'package:mobx/mobx.dart';
import '../models/question_model.dart';
import '../models/answer_model.dart';
import '../services/question_service.dart';
import 'auth_store.dart';

part 'question_store.g.dart';

class QuestionStore = _QuestionStore with _$QuestionStore;

abstract class _QuestionStore with Store {
  final QuestionService _questionService = QuestionService();
  final AuthStore _authStore;

  _QuestionStore(this._authStore);

  @observable
  ObservableList<QuestionModel> questions = ObservableList<QuestionModel>();

  @observable
  QuestionModel? selectedQuestion;

  @observable
  bool isLoading = false;

  @observable
  String? errorMessage;

  @computed
  List<QuestionModel> get hotQuestions =>
      questions.where((q) => q.isHot).toList();

  @computed
  List<QuestionModel> get userQuestions {
    if (_authStore.currentUser == null) return [];
    return questions
        .where((q) => q.userId == _authStore.currentUser!.id)
        .toList();
  }

  @action
  Future<void> loadQuestions() async {
    isLoading = true;
    errorMessage = null;

    try {
      final allQuestions = _questionService.getAllQuestions();
      questions.clear();
      questions.addAll(allQuestions);
      isLoading = false;
    } catch (e) {
      errorMessage = 'Load questions failed: ${e.toString()}';
      isLoading = false;
    }
  }

  @action
  Future<QuestionModel?> createQuestion(String content) async {
    if (_authStore.currentUser == null) return null;

    isLoading = true;
    errorMessage = null;

    try {
      final question = await _questionService.createQuestion(
        userId: _authStore.currentUser!.id,
        content: content,
      );

      questions.add(question);
      isLoading = false;
      return question;
    } catch (e) {
      errorMessage = 'Create question failed: ${e.toString()}';
      isLoading = false;
      return null;
    }
  }

  @action
  Future<AnswerModel?> addAnswer(String questionId, String content) async {
    if (_authStore.currentUser == null) return null;

    isLoading = true;
    errorMessage = null;

    try {
      final answer = await _questionService.addAnswer(
        questionId: questionId,
        userId: _authStore.currentUser!.id,
        content: content,
      );

      // 更新本地状态
      final questionIndex = questions.indexWhere((q) => q.id == questionId);
      if (questionIndex >= 0) {
        questions[questionIndex] =
            _questionService.getQuestionById(questionId)!;
      }

      if (selectedQuestion?.id == questionId) {
        selectedQuestion = _questionService.getQuestionById(questionId);
      }

      isLoading = false;
      return answer;
    } catch (e) {
      errorMessage = 'Add answer failed: ${e.toString()}';
      isLoading = false;
      return null;
    }
  }

  @action
  void selectQuestion(String questionId) {
    selectedQuestion = _questionService.getQuestionById(questionId);
  }

  @action
  Future<void> deleteQuestion(String questionId) async {
    isLoading = true;
    errorMessage = null;

    try {
      await _questionService.deleteQuestion(questionId);
      questions.removeWhere((q) => q.id == questionId);
      if (selectedQuestion?.id == questionId) {
        selectedQuestion = null;
      }
      isLoading = false;
    } catch (e) {
      errorMessage = 'Delete question failed: ${e.toString()}';
      isLoading = false;
    }
  }

  @action
  Future<void> deleteAnswer(String questionId, String answerId) async {
    isLoading = true;
    errorMessage = null;

    try {
      await _questionService.deleteAnswer(questionId, answerId);

      // 更新本地状态
      final questionIndex = questions.indexWhere((q) => q.id == questionId);
      if (questionIndex >= 0) {
        questions[questionIndex] =
            _questionService.getQuestionById(questionId)!;
      }

      if (selectedQuestion?.id == questionId) {
        selectedQuestion = _questionService.getQuestionById(questionId);
      }

      isLoading = false;
    } catch (e) {
      errorMessage = 'Delete answer failed: ${e.toString()}';
      isLoading = false;
    }
  }
}
